package pactexample339

import au.com.dius.pact.consumer.PactVerificationResult
import au.com.dius.pact.consumer.groovy.PactBuilder
import feign.Feign
import feign.gson.GsonDecoder
import feign.httpclient.ApacheHttpClient
import grails.testing.mixin.integration.Integration
import grails.transaction.*
import spock.lang.*

import java.text.ParseException
import java.text.SimpleDateFormat

@Integration
@Rollback
class PactExampleCliContractTestingSpec extends Specification {

    void "test PactExampleCli#sample"() {
        given:
        def user = "CDC"
        def mockProvider = new PactBuilder()
        mockProvider {
            serviceConsumer "PactExampleCli"    // Define the service consumer by name
            hasPactWith "PactExample"   // Define the service provider that it has a pact with
            //port 1234 // The port number for the service. It is optional, leave it out to use a random one

            //given('there is a rest api') // defines a provider state. It is optional.
            uponReceiving('a request to GET result of /sample') // upon_receiving starts a new interaction
            withAttributes(method: 'GET', headers: [Accept: "application/json;charset=UTF-8"], path: '/sample', query: [user: user])
            // define the request, a GET request to '/sample'
            willRespondWith(status: 200)
            withBody(mimeType: JSON.toString()) {
                field1(regexp(/hello\s([\w+]{0,}|world)/, "hello $user"))
                field2(integer(5))
                field3(timestamp("yyyy-MM-dd'T'HH:mm:ss'Z'", "2019-05-06T16:17:18Z"))
            }
        }

        when:
        def result = mockProvider.runTest { mockServer ->
            def pactExampleCli = Feign.builder().client(new ApacheHttpClient())
                    .decoder(new GsonDecoder()).target(PactExampleCli.class, mockServer.url as String)

            def resp = pactExampleCli.sample(user)
            assert resp instanceof Map

            assert resp.field1 == "hello " + user
            assert resp.field2 == 5
            assert resp.field3 == "2019-05-06T16:17:18Z"
        }

        then:
        result == PactVerificationResult.Ok.INSTANCE
    }
}
